
from fastapi import Form
from src.core.session import *
from src.entity.models import BaseMenu, Menu, CreateMenu, UpdateMenu, BasicModel
from src.common.response import success_response, fail_response
from src.common.status import CLASS_STATUS
from src.utils.tools import get_cur_time
from src.core.logconfig import log
from src.common.base_router import BaseRouter
from src.common.base_service import BaseService

sc = SQLCON
menu = BaseRouter(
    entity=Menu,
    create_schema=CreateMenu,
    update_schema=UpdateMenu,
    prefix="/sys/menu",
    tags=["Menu"]
).router

menu_service = BaseService(Menu)


async def query_all():
    log.logger.info(f"getMenuList item: {sc.db_query(Menu)}")
    return menu_service.get_list()

async def query_data(id):
    return menu_service.get_by_id(id)

@menu.post("/getMenus")
async def query_all_enable():
    # 封装菜单&子菜单数据
    # 如果父节点不为null，则根据该数据查询节点数据，直到节点回归null或空值
    resp = sc.db_query_filter(Menu, select(Menu).where(Menu.is_root == "1").where(Menu.state == "1").order_by(Menu.rank))
    menus = []
    for r in resp:
        r = r._to_dict()
        # log.logger.info(f"resp items: {r}")
        r['children'] = []
        # 判断当前目录是否有子目录，如果有，则将子菜单数据导入
        if r['child_node'] is not None:
            clis = []
            print(f"cl:{r} {r['child_node']}")
            cl = r['child_node'].split(",")
            for c in cl:
                print(f"cl: {cl}")
                child = sc.db_query_by_id(Menu, c)
                if child and child.state == 1:
                    clis.append( child._to_dict())
            r['children'] = clis
        menus.append(r)
    return success_response(menus)

async def create(
    name: str=Form(),
    name_zh: str=Form(),
    type:str=Form(default='element-icon'),
    path:str=Form(default=""),
    icon:str=Form(default=""),
    color:str=Form(default=""),
    desc:str=Form(default=""),
    rank:int=Form(default=1),
    child_node:str=Form(default=''),
    scale:float=Form(default=1.2),
    margin:int=Form(default=5),
    is_root:int=Form(default=1),
    state:int=Form(default=1)):
    careate_data = CreateMenu(
        name=name,
        name_zh=name_zh,
        type=type,
        path=path,
        color=color,
        desc=desc,
        rank=rank,
        child_node=child_node,
        icon=icon,
        scale=scale,
        margin=margin,
        create_time=get_cur_time(),
        is_root=is_root,
        state=state
    )
    return menu_service.create(careate_data)

async def update(
    id:int=Form(),
    name: str=Form(),
    name_zh: str=Form(),
    type:str=Form(default='element-icon'),
    path:str=Form(default=""),
    icon:str=Form(default=""),
    color:str=Form(default=""),
    desc:str=Form(default=""),
    rank:int=Form(default=1),
    child_node:str=Form(default=''),
    scale:float=Form(default=1.2),
    margin:int=Form(default=5),
    is_root:int=Form(default=1),
    state:int=Form(default=1)):
    update_data = UpdateMenu(
        id=id,
        name=name,
        name_zh=name_zh,
        type=type,
        path=path,
        color=color,
        desc=desc,
        rank=rank,
        child_node=child_node,
        icon=icon,
        scale=scale,
        margin=margin,
        update_time=get_cur_time(),
        is_root=is_root,
        state=state
    )
    return menu_service.update(update_data)

async def query_one(data: BasicModel):
    update_data = UpdateMenu(
        id=data.id,
        state=CLASS_STATUS["STATE_DELETED"],
        update_time=get_cur_time(),
    )
    return menu_service.update(update_data)
